#include "sort.h"

/** @fn     sortBubble(item *wRoot, int dir)
    @brief  sorts a list using the bubblesort algorithm
    @param  wRoot   the pointer to the list
    @param  dir     the direction of the sort action (1 = descending, 2 = ascending);
    @return 1 on succesful sort, NULL on fail
    */
/******************  pseudocode  ******************
procedure bubbleSort( A : list of sortable items ) defined as:
  do
    swapped := false
    for each i in 0 to length(A) - 2 inclusive do:
      if A[i] > A[i+1] then
        swap( A[i], A[i+1] )
        swapped := true
      end if
    end for
  while swapped
end procedure
*/
int sortBubble(item *wRoot, int dir){
    //exit function upon invalid parameter
    if(!wRoot){return((int) NULL);}
    item *ptr = wRoot;

    if(DEBUG){printf("\nsorting 0x%X", (int) wRoot);}
    //implementation of bubblesort algorithm

    //bool to check wether swapped has been executed
    int swapped = (int) NULL;

    do{
        //clear bool for each iteration
        ptr = wRoot;
        swapped = (int) NULL;

        //step through list
        while(ptr->next != (item *) NULL){
            //if not in order, swap elements
            if(((ptr->content) == (char *) NULL) || ((ptr->next->content) == (char *) NULL)){
                if(DEBUG>2){printf("\ninvalid content pointer");getchar();}
                return(0);
            }

            if(wordCompare((ptr->content), (ptr->next->content)) == 1){ //i subbed for dir
                if(DEBUG>4){printf("\nswapping 0x%X \"%s\" to 0x%X \"%s\"", (int) ptr->content, ptr->content, (int) ptr->next->content, ptr->next->content);}
                itemSwap(ptr, ptr->next);
                swapped = 1;
            }
            ptr = ptr->next;
        }
        ptr = wRoot;
    }while(swapped);

    if(DEBUG){printf("\nsort...ok"); getchar();}

    return(1);
}

/** @fn     filterClones(item *wRoot)
    @brief  removes all the clones (double entries) from a list
    @param  wRoot   the pointer to the list
    @return the amount of successful purges, NULL on fail
    */
int filterClones(item *wRoot){
    item *ptr = wRoot;
    int setchanged = 0;

    if(DEBUG){printf("\nfilter 0x%X", (int) wRoot);}

    while(ptr){
        if(ptr->next){
            while(wordCompare(ptr->content, ptr->next->content) == 0){
                itemRemove(ptr->next);
                ptr->count++;
                //increment counter
                setchanged++;
                if(!ptr->next){break;} //abort if next pointer is NULL
            }
        }
        if(DEBUG>2){printf("\nword \"%s\" detected %d times", ptr->content, ptr->count);}
        ptr = ptr->next; //goto next item
    }

    if(DEBUG){printf("\nremoving double entries...ok"); getchar();}

    return(setchanged);
}
